import axios from 'axios'
import router from '../router'
import { getToken, setToken, setEmail } from './tools'
import { Message } from 'element-ui'
class HttpRequest {
  constructor (baseUrl = '') {
    this.baseUrl = baseUrl
    this.queue = {}
  }
  getInsideConfig () {
    const config = {
      baseURL: this.baseUrl,
      headers: {
        'Authorization': 'Bearer ' + getToken()
      }
    }
    return config
  }
  destroy (url) {
    delete this.queue[url]
    if (!Object.keys(this.queue).length) {
      // Spin.hide()
    }
  }
  interceptors (instance, url) {
    // 请求拦截
    instance.interceptors.request.use(config => {
      const conf = config
      if ( conf.params && 
           conf.params.from !== undefined && 
           conf.params.size !== undefined ) {
        const pageIndex = conf.params.from
        const pageSize = conf.params.size
        if(pageIndex > 0) {
          conf.params.from = (pageIndex - 1) * pageSize 
        }
      }
      // 添加全局的loading...
      if (!Object.keys(this.queue).length) {
        // Spin.show() // 不建议开启，因为界面不友好
      }
      this.queue[url] = true
      return conf
    }, error => {
      return Promise.reject(error)
    })
    // 响应拦截
    instance.interceptors.response.use(res => {
      this.destroy(url)
      const { data, status } = res
      return { data, status }
    }, error => {

      if(error.response && error.response.data === 'Server error (Error 2).') {
        Message('数据库出错')
      } else if (error.response && error.response.data === 'Server error (Error 3).') {
        Message('数据库出错')
      }

      // token 过期
      if(error.message.lastIndexOf('401') !== -1) {
        setToken('')
        setEmail('')
        Message('登录状态已过期，请重新登录！')
        router.push('login')
      }
      this.destroy(url)
      return Promise.reject(error)
    })
  }
  request (options) {
    const instance = axios.create()
    options = Object.assign(this.getInsideConfig(), options)
    this.interceptors(instance, options.url)
    return instance(options)
  }
}
export default HttpRequest
